package im.yisme.model.fileio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import im.yisme.model.Lyrics;
import im.yisme.model.LyricsAction;
import im.yisme.model.LyricsHeader;

public class LyricsWriter {

	private String postfix = ".ylrc";
	private String path = "";
	
	public LyricsWriter(){
		path = DirManager.getLyricsDir();
		createPath();
	}
	
	/**
	 * 创建路径
	 */
	private void createPath(){
		File file = new File(path);
		file.mkdirs();
	}
	
	/**
	 * 将歌谱数据写入文件
	 * @param lyrics
	 * @throws IOException
	 */
	public void write(Lyrics lyrics) throws IOException{
		File file = new File(path + lyrics.getId() + postfix);
		FileOutputStream fos = new FileOutputStream(file);
		LyricsHeader header = lyrics.getLyricsHeader();
		ArrayList<LyricsAction> actions = lyrics.getLyricsActions();
		int usedSize = 0;
		
		writeData(fos, header.getRemoteId(), 4);
		usedSize += 4;
		
		writeData(fos, header.getTotalTime(), 4);
		usedSize += 4;
		
		int totalSize = actions.size();
		writeData(fos, totalSize, 2);
		usedSize += 2;
		
		int isUploaded = header.isUploaded() ? 1 : 0;
		writeData(fos, isUploaded, 1);
		usedSize += 1;
		
		int isEvaluated = header.isEvaluated() ? 1 : 0;
		writeData(fos, isEvaluated, 1);
		usedSize += 1;
		
		for (int i=0; i<32 - usedSize; i++){
			writeData(fos, 0, 1);
		}
		
		for(int i=0; i<totalSize; i++){
			LyricsAction action = actions.get(i);
			int actionInfo = action.toBinary();
			writeData(fos, actionInfo, 4);
		}
		
		fos.close();
	}
	
	/**
	 * 将data以bytes个字节的大小写入fos
	 * @param fos
	 * @param data
	 * @param bytes
	 * @throws IOException
	 */
	private void writeData(FileOutputStream fos, long data, int bytes) throws IOException{
		for (int i=bytes - 1; i>=0; i--){
			int temp = (int)data >> (i * 8);
			fos.write(temp);
		}
	}
}
